﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Windows;
using System.Windows.Input;

namespace UpdaterAppWPF
{
    /// <summary>
    /// Interaction logic for CheckInitialSettings.xaml
    /// </summary>
    public partial class CheckInitialSettings : Window
    {
        #region Delegates

        public delegate void FetchDataDelegate();

        #endregion

        private List<string> lstFileNames;

        private double m_iExpanderHeight = 0;

        public CheckInitialSettings()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(CheckInitialSettings_Loaded);
            this.expndr.Expanded += new RoutedEventHandler(expndr_Expanded);
            this.expndr.Collapsed += new RoutedEventHandler(expndr_Collapsed);
            m_iExpanderHeight = this.expndr.Height;
        }

        void expndr_Collapsed(object sender, RoutedEventArgs e)
        {
            ActionWhenCollapsed();
        }

        void expndr_Expanded(object sender, RoutedEventArgs e)
        {
            ActionWhenExpanded();
        }

        void CheckInitialSettings_Loaded(object sender, RoutedEventArgs e)
        {
            StartFechingData();
        }

        void StartFechingData()
        {
            //Open a thread asynchronously and fetch data
            FetchDataDelegate fetchDelegate = new FetchDataDelegate(FetchData);

            IAsyncResult result = fetchDelegate.BeginInvoke(FetchCompleted, null);
            
        }

        void FetchData()
        {
            string sCurrDir = Directory.GetCurrentDirectory();
            lstFileNames = new List<string>();

            string[] sFiles =  Directory.GetFiles(sCurrDir,"*.*", SearchOption.AllDirectories);

            foreach (string fullFileName in sFiles)
            {
                string fileName = Path.GetFileName(fullFileName);
                if (IsFileBeingUsedName(fullFileName))
                {
                    if(!CheckIfTheFileIsUpdaterFile(fileName))
                    lstFileNames.Add(fileName);
                }

            }
            
        }

        bool CheckIfTheFileIsUpdaterFile(string fileName)
        {
                       
            string sFiles = ConfigurationManager.AppSettings["UpdaterFiles"];
            char[] seperator = { ',' };
            string[] FileCollection = sFiles.Split(seperator);

            foreach (string sFile in FileCollection)
            {
                if (sFile.Equals(fileName, StringComparison.CurrentCultureIgnoreCase))
                {
                    return true;
                }
            }

            return false;
        }

        void FetchCompleted(IAsyncResult result)
        {
            //Added for debugging 
            //if (lstFileNames.Contains("FtpUploadClient.vshost.exe"))
            //    lstFileNames.Remove("FtpUploadClient.vshost.exe");
            Dispatcher.Invoke((Action)(delegate { expndr.IsExpanded = true;

            if (lstFileNames.Count == 0)
            {
                MainWindow mainWindow = new MainWindow();
                mainWindow.Show();

                this.Close();
            }
            else
            {


                foreach (string sFileName in lstFileNames)
                {

                    ListItemWPF listItem = new ListItemWPF();
                    listItem.OpenFileName = sFileName;
                    lstOpenFile.Items.Add(listItem);

                }

                pbCheck.IsIndeterminate = false;
                pbCheck.Value = pbCheck.Maximum;
                imgProceed.Visibility = Visibility.Visible;
            }
            
            }));
          
            
        }

        private bool IsFileBeingUsedName(string fileName)
        {
            bool isFileUsed = false;

            try
            {
                using (FileStream fs = File.Open(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
                {
                    fs.Close();
                }

            }
            catch (IOException)
            {

                isFileUsed = true;
            }

            return isFileUsed;
        }

        private void imgProceed_MouseDown(object sender, MouseButtonEventArgs e)
        {
            pbCheck.Value = pbCheck.Minimum;
            pbCheck.IsIndeterminate = true;
            lstOpenFile.Items.Clear();
            StartFechingData();
        }

        private void ActionWhenCollapsed()
        {
            this.lstOpenFile.Visibility = Visibility.Hidden;
        }

        private void ActionWhenExpanded()
        {
            this.lstOpenFile.Visibility = Visibility.Visible;
           
        }
    }
}
